#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_batch_start.sh
##  Functions : 跑批开始
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
##  2.0      2018-11-11  薛周毅           1.更新表【EDW_BATCH_DATE】的开始时间
##                                        2.根据表【EDW_JOB_CONTROL】初始化表【EDW_JOB_STATUS】
##                                        3.检查是否有作业任务来更新表【EDW_BATCH_DATE】
###############################################################################

:<<!
   错误码： 1  清除历史跑批失败
            2  更新跑批记录失败
            3  清除本期历史任务日志失败
            4  添加任务到任务日志失败
            5  查询任务数量失败
!

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

V_DATA_DATE=$(grep "#V_DATA_DATE#" ${V_PARM_FILE} | awk -F'=' '{print $2}')
V_FREQUENCY=$(grep "#V_FREQUENCY#" ${V_PARM_FILE} | awk -F'=' '{print $2}')
# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_DATA_DATE}/${V_SCRIPT_NAME}_${V_FREQUENCY}.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output

BEGIN
LOGGER "INFO" "Today batch date is ${V_DATA_DATE}."

# 清除本期历史跑批记录
V_QUERY="DELETE FROM ETL.EDW_BATCH_DATE WHERE DATA_DATE='${V_DATA_DATE}'"
${V_RUN_DB} -q "${V_QUERY}" || exit 1


# 加入本次跑批记录
V_QUERY="INSERT INTO  ETL.EDW_BATCH_DATE (DATA_DATE,START_TIME) VALUES('${V_DATA_DATE}','$(NOW)')"
${V_RUN_DB} -q "${V_QUERY}" || exit 2


# 清除本期历史任务日志
V_QUERY="DELETE FROM ETL.EDW_JOB_STATUS WHERE DATA_DATE='${V_DATA_DATE}' AND JOB_FREQUENCY='${V_FREQUENCY}'"
${V_RUN_DB} -q "${V_QUERY}" || exit 3


# 添加任务到任务日志表
V_QUERY="INSERT INTO ETL.EDW_JOB_STATUS(DATA_DATE,JOB_TYPE,JOB_FREQUENCY,JOB_DAY,JOB_GROUP,SEQ_NO,PROC_NAME) SELECT '${V_DATA_DATE}',JOB_TYPE,JOB_FREQUENCY,JOB_DAY,JOB_GROUP,SEQ_NO,PROC_NAME FROM ETL.EDW_JOB_CONTROL WHERE JOB_FREQUENCY='${V_FREQUENCY}' AND IF_VALID='Y'"
${V_RUN_DB} -q "${V_QUERY}" || exit 4



# Check job
V_QUERY="SELECT COALESCE(COUNT(1),0) FROM ETL.EDW_JOB_STATUS WHERE DATA_DATE='${V_DATA_DATE}'"
V_JOB_CNT=$(${V_RUN_DB} -q "${V_QUERY}") || exit 5
if [[ ${V_JOB_CNT} -eq 0 ]];then
    V_QUERY="UPDATE ETL.EDW_BATCH_DATE SET STATUS='SKIP' WHERE DATA_DATE='${V_DATA_DATE}'"
    ${V_RUN_DB} -q "${V_QUERY}"
    LOGGER "INFO" "Success to update EDW_BATCH_DATE status."
else
    V_QUERY="UPDATE ETL.EDW_BATCH_DATE SET STATUS='RUN' WHERE DATA_DATE='${V_DATA_DATE}'"
    ${V_RUN_DB} -q "${V_QUERY}"
    LOGGER "INFO" "Success to update EDW_BATCH_DATE status."
fi

END
exit 0
